// 主游戏类
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 游戏状态
        this.state = GAME_STATES.MENU;
        this.isRunning = false;
        this.isPaused = false;
        
        // 视口系统
        this.camera = {
            x: 0,
            y: 0,
            width: GAME_CONFIG.CANVAS_WIDTH,
            height: GAME_CONFIG.CANVAS_HEIGHT,
            // 添加平滑跟随参数
            targetX: 0,
            targetY: 0,
            smoothFactor: 0.1 // 平滑因子，值越小越平滑
        };
        
        // 游戏时间
        this.gameTime = 0;
        this.lastTime = 0;
        
        // 游戏对象
        this.player = null;
        this.enemySpawner = null;
        this.weaponManager = null;
        this.itemSpawner = null;
        this.effectManager = null;
        this.cloneManager = null;
        this.minionManager = null;
        this.buildingManager = null;
        this.spriteManager = null;
        
        // 游戏统计
        this.enemiesKilled = 0;
        this.experienceGained = 0;
        this.survivalTime = 0;
        
        // 升级选择定时器
        this.upgradeSelectionTimer = 0;
        this.maxUpgradeSelectionTime = BALANCE_CONFIG.UPGRADE_SELECTION_TIME || 1000; // 从平衡配置获取时间
        
        this.init();
    }
    
    // 初始化游戏
    async init() {
        // 加载游戏资源
        await this.loadGameAssets();
        
        // 创建游戏对象
        this.player = new Player(GAME_CONFIG.CANVAS_WIDTH / 2, GAME_CONFIG.CANVAS_HEIGHT / 2);
        this.enemySpawner = new EnemySpawner();
        this.weaponManager = new WeaponManager(this.player);
        this.itemSpawner = new ItemSpawner();
        this.effectManager = new EffectManager();
        this.cloneManager = new CloneManager(this.player);
        this.minionManager = new MinionManager();
        this.buildingManager = new BuildingManager();
        
        // 初始化性能监控
        this.performanceMonitor = window.performanceMonitor;
        this.memoryManager = window.memoryManager;
        this.spatialHash = new SpatialHash(100); // 100像素的格子大小
        
        // 设置玩家升级回调
        this.onPlayerLevelUp = this.handlePlayerLevelUp.bind(this);
        
        // 设置全局游戏实例
        window.game = this;
        
        // 开始游戏循环
        this.gameLoop();
    }
    
    // 加载游戏资源
    async loadGameAssets() {
        try {
            // 确保精灵管理器已初始化
            if (!window.spriteManager) {
                window.spriteManager = new SpriteManager();
            }
            
            // 初始化UI素材生成器和音效生成器
            this.uiAssetGenerator = new UIAssetGenerator();
            this.soundGenerator = new SoundGenerator();
            
            // 生成UI素材
            this.uiAssets = this.uiAssetGenerator.generateAllUIAssets();
            
            // 生成音效
            this.sounds = this.soundGenerator.generateAllSounds();
            
            // 生成像素艺术资源
            const imageList = [
                { key: 'player', src: window.pixelArtGenerator.generatePlayer() },
                { key: 'enemy_basic', src: window.pixelArtGenerator.generateEnemy('basic') },
                { key: 'enemy_fast', src: window.pixelArtGenerator.generateEnemy('fast') },
                { key: 'enemy_tank', src: window.pixelArtGenerator.generateEnemy('tank') },
                { key: 'weapon_fireball', src: 'assets/images/weapons/火球.png' },
                { key: 'weapon_lightning', src: window.pixelArtGenerator.generateWeaponEffect('lightning') },
                { key: 'weapon_ice', src: 'assets/images/weapons/冰锥.png' },
                { key: 'weapon_laser', src: window.pixelArtGenerator.generateWeaponEffect('laser') },
                { key: 'weapon_orbital', src: window.pixelArtGenerator.generateWeaponEffect('orbital') },
                { key: 'weapon_shield', src: window.pixelArtGenerator.generateWeaponEffect('shield') },
                { key: 'weapon_knife', src: 'assets/images/weapons/飞刀.png' },
                { key: 'item_health', src: window.pixelArtGenerator.generateItem('health') },
                { key: 'item_experience', src: window.pixelArtGenerator.generateItem('experience') },
                { key: 'ui_button', src: window.pixelArtGenerator.generateUI('button') },
                { key: 'ui_healthBar', src: window.pixelArtGenerator.generateUI('healthBar') }
            ];
            
            // 加载所有图像
            await window.spriteManager.loadImages(imageList);
            
            // 创建精灵
            window.spriteManager.createSprite('player', 32, 32);
            window.spriteManager.createSprite('enemy_basic', 32, 32);
            window.spriteManager.createSprite('enemy_fast', 32, 32);
            window.spriteManager.createSprite('enemy_tank', 32, 32);
            window.spriteManager.createSprite('weapon_fireball', 32, 32);
            window.spriteManager.createSprite('weapon_lightning', 32, 32);
            window.spriteManager.createSprite('weapon_ice', 32, 32);
            window.spriteManager.createSprite('weapon_knife', 32, 32);
            window.spriteManager.createSprite('weapon_laser', 32, 32);
            window.spriteManager.createSprite('weapon_orbital', 32, 32);
            window.spriteManager.createSprite('weapon_shield', 32, 32);
            window.spriteManager.createSprite('item_health', 24, 24);
            window.spriteManager.createSprite('item_experience', 24, 24);
            
            console.log('精灵创建完成，可用的精灵:', Array.from(window.spriteManager.sprites.keys()));
            
            console.log('游戏资源加载完成！');
            console.log('已加载的精灵:', Object.keys(window.spriteManager.sprites));
        } catch (error) {
            console.error('资源加载失败:', error);
        }
    }
    
    // 游戏主循环
    gameLoop() {
        const currentTime = performance.now();
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        // 更新性能监控
        if (this.performanceMonitor) {
            this.performanceMonitor.update();
        }
        
        if (this.isRunning && !this.isPaused && (this.state === GAME_STATES.PLAYING || this.state === GAME_STATES.UPGRADING)) {
            this.update(deltaTime);
        }
        
        this.render();
        
        requestAnimationFrame(() => this.gameLoop());
    }
    
    // 更新游戏状态
    update(deltaTime) {
        try {
            // 只在游戏进行中更新游戏时间
            if (this.state === GAME_STATES.PLAYING) {
                this.gameTime += deltaTime;
                this.survivalTime = this.gameTime / 1000;
            }
            
            // 在游戏进行中或升级中更新游戏对象
            if (this.state === GAME_STATES.PLAYING || this.state === GAME_STATES.UPGRADING) {
                // 更新玩家
                if (this.player) this.player.update(deltaTime);
                
                // 更新视口
                this.updateCamera();
                
                // 更新敌人生成器
                if (this.enemySpawner) this.enemySpawner.update(deltaTime, this.player);
                
                // 更新武器管理器
                if (this.weaponManager && this.enemySpawner) {
                    this.weaponManager.update(deltaTime, this.enemySpawner.getEnemies());
                }
                
                // 更新道具生成器
                if (this.itemSpawner) this.itemSpawner.update(deltaTime, this.player);
                
                // 更新特效管理器
                if (this.effectManager) this.effectManager.update(deltaTime);
                
                // 更新分身管理器
                if (this.cloneManager && this.enemySpawner) {
                    this.cloneManager.update(deltaTime, this.enemySpawner.getEnemies());
                }
                
                // 更新小兵管理器
                if (this.minionManager && this.enemySpawner) {
                    this.minionManager.update(deltaTime, this.enemySpawner.getEnemies());
                }
                
                // 更新建筑管理器
                if (this.buildingManager) {
                    this.buildingManager.update(deltaTime);
                }
                
                // 更新粒子系统
                if (window.particleSystem) {
                    window.particleSystem.update(deltaTime);
                }
                
                // 只在游戏进行中检查碰撞和游戏结束
                if (this.state === GAME_STATES.PLAYING) {
                    // 检查玩家与敌人的碰撞
                    this.checkPlayerEnemyCollisions();
                    
                    // 检查游戏结束条件
                    this.checkGameOver();
                }
            }
            
            // 更新UI
            if (uiManager) uiManager.updateGameUI(this.player, this.survivalTime);
            
            // 内存清理
            if (this.memoryManager) {
                this.memoryManager.cleanup(this);
            }
        } catch (error) {
    
        }
    }
    
    // 更新视口
    updateCamera() {
        if (!this.player) return;
        
        // 计算目标视口位置（跟随玩家）
        this.camera.targetX = this.player.x - this.camera.width / 2;
        this.camera.targetY = this.player.y - this.camera.height / 2;
        
        // 平滑跟随玩家
        this.camera.x += (this.camera.targetX - this.camera.x) * this.camera.smoothFactor;
        this.camera.y += (this.camera.targetY - this.camera.y) * this.camera.smoothFactor;
        
        // 限制视口在世界范围内
        this.camera.x = Utils.clamp(this.camera.x, 0, GAME_CONFIG.WORLD_WIDTH - this.camera.width);
        this.camera.y = Utils.clamp(this.camera.y, 0, GAME_CONFIG.WORLD_HEIGHT - this.camera.height);
    }
    
    // 渲染游戏
    render() {
        try {
            // 清空画布
            this.ctx.fillStyle = '#000000';
            this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
            
            // 在游戏进行中或暂停时都渲染游戏对象
            if (this.state === GAME_STATES.PLAYING || this.state === GAME_STATES.UPGRADING) {
                // 保存当前上下文状态
                this.ctx.save();
                
                // 应用视口变换
                this.ctx.translate(-this.camera.x, -this.camera.y);
                
                // 渲染游戏对象
                if (this.player) this.player.render(this.ctx);
                if (this.enemySpawner) this.enemySpawner.render(this.ctx);
                if (this.weaponManager) this.weaponManager.render(this.ctx);
                if (this.itemSpawner) this.itemSpawner.render(this.ctx);
                if (this.effectManager) this.effectManager.render(this.ctx);
                if (this.cloneManager) this.cloneManager.render(this.ctx);
                if (this.minionManager) this.minionManager.render(this.ctx);
                if (this.buildingManager) this.buildingManager.render(this.ctx);
                
                // 渲染粒子系统
                if (window.particleSystem) {
                    window.particleSystem.render(this.ctx);
                }
                
                // 渲染世界边界（可选）
                this.renderWorldBounds();
                
                // 恢复上下文状态
                this.ctx.restore();
            }
            
            // 调试信息：在画布上显示游戏状态
            this.ctx.fillStyle = '#ffffff';
            this.ctx.font = '12px Arial';
            this.ctx.fillText(`状态: ${this.state}`, 10, 20);
            this.ctx.fillText(`运行: ${this.isRunning}`, 10, 35);
            this.ctx.fillText(`暂停: ${this.isPaused}`, 10, 50);
            this.ctx.fillText(`武器数量: ${this.weaponManager ? this.weaponManager.weapons.length : 0}`, 10, 65);
            this.ctx.fillText(`分身数量: ${this.cloneManager ? this.cloneManager.getCloneCount() : 0}`, 10, 80);
            this.ctx.fillText(`小兵数量: ${this.minionManager ? this.minionManager.getMinionCount() : 0}`, 10, 95);
            this.ctx.fillText(`小兵等级: ${this.minionManager ? this.minionManager.getAverageLevel() : 0}`, 10, 110);
            this.ctx.fillText(`建筑数量: ${this.buildingManager ? this.buildingManager.getBuildingCount() : 0}`, 10, 125);
            this.ctx.fillText(`玩家位置: (${Math.round(this.player?.x || 0)}, ${Math.round(this.player?.y || 0)})`, 10, 140);
            this.ctx.fillText(`视口位置: (${Math.round(this.camera.x)}, ${Math.round(this.camera.y)})`, 10, 155);
            this.ctx.fillText(`目标位置: (${Math.round(this.camera.targetX)}, ${Math.round(this.camera.targetY)})`, 10, 170);
            this.ctx.fillText(`平滑因子: ${this.camera.smoothFactor}`, 10, 185);
            this.ctx.fillText(`世界边界: ${GAME_CONFIG.WORLD_WIDTH}x${GAME_CONFIG.WORLD_HEIGHT}`, 10, 200);
            this.ctx.fillText(`当前阶段: ${this.enemySpawner ? this.enemySpawner.stage : 1}`, 10, 215);
            this.ctx.fillText(`难度等级: ${this.enemySpawner ? this.enemySpawner.difficulty : 1}`, 10, 230);
            this.ctx.fillText(`目标位置: (${Math.round(this.camera.targetX)}, ${Math.round(this.camera.targetY)})`, 10, 155);
            this.ctx.fillText(`平滑因子: ${this.camera.smoothFactor}`, 10, 170);
            this.ctx.fillText(`世界边界: ${GAME_CONFIG.WORLD_WIDTH}x${GAME_CONFIG.WORLD_HEIGHT}`, 10, 185);
            this.ctx.fillText(`当前阶段: ${this.enemySpawner ? this.enemySpawner.stage : 1}`, 10, 200);
            this.ctx.fillText(`难度等级: ${this.enemySpawner ? this.enemySpawner.difficulty : 1}`, 10, 215);
            
            // 渲染性能监控
            if (this.performanceMonitor) {
                this.performanceMonitor.render(this.ctx);
            }
        } catch (error) {
            console.error('渲染错误:', error);
            // 显示错误信息
            this.ctx.fillStyle = '#ff0000';
            this.ctx.font = '16px Arial';
            this.ctx.fillText('渲染错误: ' + error.message, 10, 100);
        }
    }
    
    // 渲染世界边界
    renderWorldBounds() {
        this.ctx.strokeStyle = '#333333';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(0, 0, GAME_CONFIG.WORLD_WIDTH, GAME_CONFIG.WORLD_HEIGHT);
    }
    
    // 检查玩家与敌人的碰撞
    checkPlayerEnemyCollisions() {
        const enemies = this.enemySpawner.getEnemies();
        if (Array.isArray(enemies)) {
            enemies.forEach(enemy => {
                if (!enemy.isDead && this.player.collidesWith(enemy)) {
                    // 玩家受到伤害
                    const isDead = this.player.takeDamage(enemy.damage);
                    // 显示伤害数字
                    uiManager.showDamageNumber(this.player.x, this.player.y - 30, enemy.damage);
                    // 添加受伤特效
                    this.effectManager.addEffect(this.player.x, this.player.y, 'hit');
                    if (isDead) {
                        this.gameOver();
                    }
                }
            });
        }
    }
    
    // 检查游戏结束条件
    checkGameOver() {
        if (this.player.isDead()) {
            this.gameOver();
        }
    }
    
    // 游戏结束
    gameOver() {
        this.state = GAME_STATES.GAME_OVER;
        this.isRunning = false;
        
        uiManager.showGameOverScreen(this.survivalTime);
    }
    
    // 处理玩家升级
    handlePlayerLevelUp(player) {
        this.state = GAME_STATES.UPGRADING;
        this.isPaused = true;
        
        // 显示升级界面
        const upgradeOptions = this.weaponManager.getUpgradeOptions();
        uiManager.showUpgradeScreen(upgradeOptions);
        
        // 显示等级提升消息
        uiManager.showLevelUp();
    }
    
    // 开始游戏
    start() {
        this.state = GAME_STATES.PLAYING;
        this.isRunning = true;
        this.isPaused = false;
        this.gameTime = 0;
        this.lastTime = performance.now();
        
        // 重置游戏对象
        this.player.reset();
        this.enemySpawner.reset();
        this.weaponManager.reset();
        this.itemSpawner.reset();
        this.effectManager.reset();
        this.cloneManager.reset();
        this.minionManager.reset();
        this.buildingManager.reset();
        
        // 添加默认建筑
        this.buildingManager.addDefaultBuildings();
        
        // 重置统计
        this.enemiesKilled = 0;
        this.experienceGained = 0;
        this.survivalTime = 0;
    }
    
    // 暂停游戏
    pause() {
        if (this.state === GAME_STATES.PLAYING) {
            this.isPaused = true;
            uiManager.showPause();
        }
    }
    
    // 恢复游戏
    resume() {
        if (this.state === GAME_STATES.PLAYING) {
            this.isPaused = false;
            this.state = GAME_STATES.PLAYING;
            uiManager.showResume();
        }
    }
    
    // 重置游戏
    reset() {
        this.state = GAME_STATES.MENU;
        this.isRunning = false;
        this.isPaused = false;
        this.gameTime = 0;
        
        // 重置所有游戏对象
        this.player.reset();
        this.enemySpawner.reset();
        this.weaponManager.reset();
        this.itemSpawner.reset();
        this.effectManager.reset();
        this.cloneManager.reset();
        this.minionManager.reset();
        
        // 重置UI
        uiManager.reset();
    }
    
    // 应用玩家属性升级
    applyPlayerUpgrade(upgradeType) {
        if (!this.player) return;
        
        switch(upgradeType) {
            case 'speed':
                this.player.speed *= 1.2;
                break;
            case 'health':
                this.player.maxHealth += 20;
                this.player.health += 20;
                break;
            case 'regen':
                // 添加生命恢复效果
                this.player.healthRegen = true;
                this.player.healthRegenRate = 1; // 每秒恢复1点
                break;
        }
    }
    
    // 获取游戏统计
    getStats() {
        return {
            survivalTime: this.survivalTime,
            enemiesKilled: this.enemiesKilled,
            experienceGained: this.experienceGained,
            playerLevel: this.player.level,
            playerHealth: this.player.health
        };
    }
    
    // 获取升级所需经验
    getExperienceForNextLevel() {
        return getCumulativeExperienceForLevel(this.player.level + 1);
    }
    
    // 检查升级
    checkUpgrade() {
        if (this.player.experience >= this.getExperienceForNextLevel()) {
            this.player.level++;
            this.player.experience -= this.getExperienceForNextLevel();
            this.state = GAME_STATES.UPGRADING;
            this.upgradeSelectionTimer = this.maxUpgradeSelectionTime;
            
            // 播放升级音效
            if (this.soundGenerator && this.sounds.upgrade) {
                this.soundGenerator.playSound(this.sounds.upgrade);
            }
        }
    }
    
    // 更新升级界面
    updateUpgrade(deltaTime) {
        // 更新升级选择倒计时
        this.upgradeSelectionTimer -= deltaTime;
        
        // 如果时间到了，自动选择一个升级
        if (this.upgradeSelectionTimer <= 0) {
            this.autoSelectUpgrade();
        }
    }
    
    // 自动选择升级
    autoSelectUpgrade() {
        const options = this.ui.getUpgradeOptions();
        if (options.length > 0) {
            const randomIndex = Math.floor(Math.random() * options.length);
            this.selectUpgrade(options[randomIndex]);
        }
    }
}

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        if (window.game) {
            if (window.game.state === GAME_STATES.PLAYING) {
                if (window.game.isPaused) {
                    window.game.resume();
                } else {
                    window.game.pause();
                }
            }
        }
    }
});

// 当页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    new Game();
}); 